package com.liuche.framework.biz.context.filter;

import com.liuche.framework.biz.context.holder.UserContextHolder;
import com.liuche.framework.common.constant.GlobalConstants;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author：liuche
 * @Date：2024年07月07日 16:43
 * @Description：用户ID过滤器
 */
@Slf4j
public class UserContextFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String userId = request.getHeader(GlobalConstants.HEADER_USER_ID);
        if (StringUtils.isNotBlank(userId)) {
            UserContextHolder.setUserId(userId);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            // 一定要删除 ThreadLocal ，防止内存泄露
            UserContextHolder.remove();
            log.info("===== 删除 ThreadLocal， userId: {}", userId);
        }
    }
}
